<template>
	<view class="content">
		<iframe allow="camera *;microphone *; display-capture" allowfullscreen="true" border="0" v-if="isVideoLive" webkitallowfullscreen="true" mozallowfullscreen="true" :src="url" frameborder="0" width="100%" height="100%"></iframe>
		<!-- <view class="back" @click="onBack">
			<tui-icon name="home-fill" :size="34" color="#999"></tui-icon>
		</view>
		<view class="back" @click="qiandao" style="bottom: 46vh;right: 30rpx;z-index: 999999;">
			<image src="/web/static/qiandao_1.png" mode="" style="width: 100rpx;height: 100rpx;"></image>
		</view> -->
		<view class="hongbaoyu" v-if="isHongbao">
			<view class="ready" ref="ready" v-if="readyStatus">
				{{ready}}
			</view>
			<view class="top">
				<view class="left">
					剩余时间：{{downTime}}
				</view>
				<view class="right">
					抢到红包：{{redNumber}}
				</view>
			</view>
			<view class="redBox" v-for="(item,index) in redBox" :key="index" v-if="gameStatus == 2">
				<image class="red" :style="{
					width:item.width,
					left: item.left,
					transform: item.transform,
					animationDuration: item.animationDuration
				}" :data-index="index"  src="@/static/redBoxRain/close.png" mode="widthFix" @touchend="rob" v-if="item.status">
				</image>
				
				<image class="red" :style="{
					width:item.width,
					left: item.left,
					transform: item.transform,
					animationDuration: item.animationDuration
				}" :src="item.suiji" mode="widthFix"  v-else>
				</image>
				
			</view>
			<view class="endBox" v-if="gameStatus == 3">
				<view class="head">
					游戏结束
				</view>
				<view class="info">
					<view class="star">
						<image class="star-item" v-for="item1 in stars"  :key="index" :src="item1" mode="widthFix"></image>
					</view>
					<view class="tips" style="line-height: 1.8;">
						<view class="">本轮红包雨一共抢到{{redNumber}}个红包</view>
						<view class="">已兑换微信红包{{click_red_rain_amount||0}}元</view>
					</view>
					<view class="btn" @tap="align">
						关闭
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				isPlaySource: false, //是否有播放源
				isVideoLive: false, //是否是直播
				isAutoplay: true, //是否自动播放
				videoMsg: '', //video消息
				currentUrl: '', //播放路径
				showControlbar: true,
				timer:null,
				url:'',
				image:'',
				id:'',
				course_name:'',
				page:1,
				// 红包生产速度
				rate: 400,
				// 红包雨集合
				redBox: [],
				// ready状态
				readyStatus: false,
				ready: 'ready',
				// 游戏时长
				downTime: 0,
				// 游戏结束定时器
				endTimer: null,
				// 获得红包个数
				redNumber: 0,
				// 游戏状态
				gameStatus: 1,
				// 游戏评分
				stars: [
					'../../static/redBoxRain/starOff.png',
					'../../static/redBoxRain/starOff.png',
					'../../static/redBoxRain/starOff.png',
					'../../static/redBoxRain/starOff.png',
					'../../static/redBoxRain/starOff.png'
				],
				isHongbao:false,
				click_red_rain_amount:'',
				heartbeatInterval:20000, // 20 秒
				heartbeatTimer:null,
				ws:null,
				socket:null,
				is_open_socket:false,
				reconnectTimeOut:null,
				ticket_id:''
			}
		},
		
		onLoad(e) {
			let that = this
			if(this.tui.isLogin()){
				
				this.id=e.zhiboid
				this.getList()
				this.getJianting()
			}else{
				uni.setStorageSync('refCode', e.inviter_code)
				uni.setStorageSync('zhiboid', e.zhiboid)
				uni.redirectTo({
					url: '/pages/login/login'
				})
			}
			// this.url =uni.getStorageSync('zhiboUrl')
		},
		// #ifdef MP
		onShareAppMessage() {
			return {
				title:'分享海报',
				path:'/pages/home/home?inviter_code='+uni.getStorageSync('inviter_code')+'&zhiboid='+this.id,
				imageUrl:this.image||'/static/logo.jpg'
			};
		},
		// #endif
		onShow() {
			let that = this
			that.isVideoLive = true
			if(that.tui.isLogin()){
				that.tui.TongjiLive(1, this.id)
			}
		},
		onHide() {
			// alert(2222)
			let that = this
			that.isVideoLive = false
			if(uni.getStorageSync('lookLive')==1){
				that.tui.TongjiLive(2, this.id)
			}
			
		},
		onBackPress() {
			// alert(3333)
			let that = this
			that.isVideoLive = false
			if(uni.getStorageSync('lookLive')==1){
				that.tui.TongjiLive(2, this.id)
			}
		},
		onUnload() {
			// alert(4444)
			let that = this
			if(that.is_open_socket){
				that.ws.close()
			}
			that.is_open_socket = false
			that.isVideoLive = false
			if(uni.getStorageSync('lookLive')==1){
				that.tui.TongjiLive(2, this.id)
			}
		},
		methods: {
			onBack(){
				uni.switchTab({
					url:'/pages/home/home'
				})
				// uni.navigateTo({
				// 	url:'/pages/MyOrderList/MyOrderList'
				// })
			},
			
			qiandao(){
				console.log(1111)
				this.tui.href('/pages/SignIn/SignIn')
			},
			onMessage(e) {
				let that = this
				that.tui.href('/pages/ConfirmOrder/ConfirmOrder?order_no='+e.detail.data)
			  console.log('Received message from web page:', e.detail.data);
			},
			getJianting(){
				let that = this
				window.addEventListener('message', function (event) {
				    // 获取消息内容
				    var messageEvent = event.data;
				 
				    // 打印消息内容
				    // 检查 messageEvent 是否存在或者是一个对象类型。
				    if (!messageEvent || typeof messageEvent !== 'object') {
				        // 输出错误信息 'Received invalid message event:'，并将 messageEvent 的值打印出来。
				        console.error('Received invalid message event:', messageEvent);
				        // 返回（结束当前函数的执行）。
				        return;
				    }
				    // 检查消息类型是否为 "vhOpenHref"，并提取URL
				    if (messageEvent.type === 'vhOpenHref' && typeof messageEvent.data === 'string') {
				 
				        // 在移动端浏览器上运行的逻辑
						that.tui.href('/pages/GoodsDetails/GoodsDetails?id='+that.getParam(messageEvent.data,'id'))
				         // window.location.href = messageEvent.data;
				 
				    } else {
						
				    }
				});
			},
			getParam(path, name) {
				  var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");   
				  if (reg.test(path))  
				  return unescape(RegExp.$2.replace(/\+/g, " ")); 
				  return "";    
			},
			getList(){
				let that = this
				let data = {}
				that.tui.request('api.auth.room/roomListAll', "POST", {page:that.page}, false, false, true).then((res) => {
					if(res.code==1){
						res.data.list.map(item=>{
							if(that.id==item.id){
								that.url = item.url
								uni.setStorageSync('zhiboStatus',item)
								data.title = uni.getStorageSync('shareTitle')
								data.desc = item.name
								data.share_img = item.cover
								uni.setStorageSync('shareZhibo', data)
								that.tui.wxShare(1,item.id)
								that.ticket_id = item.room_id
								// let url = "wss://socket-shop.zzcyx1688.cn/admin/orderSocket/connect?project_name=live40&token="+uni.getStorageSync("d_token")+"&scene=red_rain&ticket_id="+item.room_id
								let url = "wss://socket.zzcyx1688.cn/ws"
								// that.socketIo.connectSocketInit(url)
								that.getscokt(url)
							}
						})
					}
				}).catch((res) => {
					
				})
			},
			getscokt(url){
				let that = this
				that.ws = new WebSocket(url);
				try {
				    // ws连接成功
				    that.ws.onopen = function () {
				        console.log("WebSocket Server [" + url + "] 连接成功！");
						that.is_open_socket = true
						clearTimeout(that.reconnectTimeOut)
				        that.startHeartbeat();
						let data = {'type':'logins','user_id':'666','ticket_id':that.ticket_id}
						that.ws.send(JSON.stringify(data));
				    };
				    // ws连接关闭
				    that.ws.onclose = function () {
				        if (that.ws) {
				            that.ws.close();
				            that.ws = null;
				        }
				        console.log("WebSocket Server [" + url + "] 连接关闭！1");
				        that.stopHeartbeat();
						if(that.is_open_socket){
							that.reconnectTimeOut = setTimeout(()=>{
								that.getscokt(url);
							},3000)
						}
				    };
				    // ws连接错误
				    that.ws.onerror = function () {
				        if (that.ws) {
				            that.ws.close();
				            that.ws = null;
				        }
				        console.log("WebSocket Server [" + url + "] 连接关闭！2");
				        that.stopHeartbeat();
				    };
				    // ws数据返回处理
				    that.ws.onmessage = function (result) {
						console.log(result)
						let rest =JSON.parse(result.data)
						console.log(rest)
						if(rest.type=='ping'){
							
						}else if(rest.type=="send_red_rain"){
							that.redBox=[],
							// ready状态
							that.readyStatus=false,
							that.ready='ready',
							// 游戏时长
							that.downTime=rest.duration,
							// 游戏结束定时器
							that.endTimer= null,
							// 获得红包个数
							that.redNumber= 0,
							// 游戏状态
							that.gameStatus= 1,
							that.isHongbao= true
							that.start()
						}
						// else if(rest.type=="ended"){
						// 	that.gameStatus = 3;
						// 	let onNumber = Math.round(that.redNumber/(that.redBox.length/5));
						// 	that.stars.fill('../../static/redBoxRain/starOn.png',0,onNumber);
						// 	that.click_red_rain_amount = rest.data.user_join_red_rain_info.click_red_rain_amount
						// }
						
				    };
				} catch (e) {
				    alert(e.message);
				}
			},
			// 启动心跳定时器
			startHeartbeat() {
				var that = this
			    that.heartbeatTimer = setInterval(function () {
			        if (that.ws && that.ws.readyState === WebSocket.OPEN) {
						let data = {'type':'pong'}
						console.log(data)
			            that.ws.send(JSON.stringify(data));
			        }
			    }, that.heartbeatInterval);
			},
			// 停止心跳定时器
			stopHeartbeat() {
				var that = this
			    clearInterval(that.heartbeatTimer);
			},
			start() {
				let that = this;
				that.gameStatus = 2;
				that.readyStatus = true;
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = '../../static/redBoxRain/music.mp3';
				innerAudioContext.onPlay(() => {
					console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
			
				let timer = setTimeout(function() {
					that.ready = 'Go';
					that.rain();
					that.down();
					let timer1 = setTimeout(function() {
						that.readyStatus = false
						clearInterval(timer1);
					}, 500)
					clearInterval(timer);
				}, 1000)
			},
			down() {
				let that = this;
				let downTimer = setInterval(function() {
					if (that.downTime == 0) {
						clearInterval(downTimer);
						if(that.redNumber!=0){
							that.submiteHb()
						}else{
							that.gameStatus = 3;
							let onNumber = Math.round(that.redNumber/(that.redBox.length/5));
							that.stars.fill('../../static/redBoxRain/starOn.png',0,onNumber);
							that.click_red_rain_amount = 0
						}
					} else {
						that.downTime--;
					}
				}, 1000)
			},
			rain() {
				let that = this;
				let win = 0;
				uni.getSystemInfo({
					success: function(res) {
						win = res.windowWidth
					}
				});
				//随机红包旋转角度
				let rotate = (parseInt(Math.random() * 90 - 45)) + "deg";
				//随机红包宽度
				let width = (parseInt(Math.random() * 50)) + 120;
				//动画时间
				let durTime = parseInt(Math.random() * 1.5) + 3 + 's';
				
				let suiji = Math.random() < 0.5 ? '/static/redBoxRain/open_kong.png' : '/static/redBoxRain/open.png'
				
				//随机红包偏移位置
				let left = parseInt(Math.random() * win);
				if (left < 100) {
					left = parseInt(Math.random() * 100) + 100
				} else if (left > (win - width)) {
					left = (win + 70)
				}
			
				that.redBox.push({
					status: true,
					width: width + 'rpx',
					left: left + 'rpx',
					transform: 'rotate(' + rotate + ')',
					animationDuration: durTime,
					suiji:suiji
				})
				// 多少时间游戏结束
				setTimeout(() => {
					clearTimeout(that.endTimer)
					return false
				}, that.downTime * 1000)
			
				// 红包密度
				that.endTimer = setTimeout(() => {
			
					that.rain();
				}, this.rate)
			},
			submiteHb(){
				let that = this
				that.tui.request("api.auth.redRainNotify/handleNotify", "POST", {token:that.tui.getToken(),ticket_id:that.ticket_id,click_red_rain_num:that.redNumber}, false, false, true).then((res) => {
					if(res.code==1){
						that.gameStatus = 3;
						let onNumber = Math.round(that.redNumber/(that.redBox.length/5));
						that.stars.fill('../../static/redBoxRain/starOn.png',0,onNumber);
						that.click_red_rain_amount = res.data.data.click_red_rain_amount
					}
				}).catch((res) => {
				
				})
				
			},
			rob(event) {
				let index = event.currentTarget.dataset.index;
				
				if(this.redBox[index].status){
					this.redBox[index].status = false;
					this.redNumber++
				}
				
				event.preventDefault();
			},
			align(){
				this.isHongbao = false
			}
		}
	}
</script>
 
 
<style lang="scss" scoped>
	.content {
		width: 100vw;
		height: 100vh;
		display: flex;
		flex-direction: column;
		.player-content {
			position: relative;
			width: 100%;
			height: 450rpx;
			display: flex;
			background-size: 100% 100%;
 
			.live-player {
				width: 100%;
				height: 100%;
				position: relative;
			}
		}
	}
	.back{
		position: fixed;
		right: 20rpx;
		bottom:40vh;
		display: flex;
		align-items: center;
		justify-content: center;z-index: 99999;
		width: 100rpx;
		height: 100rpx;
		// 返回
		.back-one{
			display: flex;
			align-items: center;
			justify-content: center;
			width: 50rpx;
			height: 50rpx;
			background-color: rgba(0,0,0,0.3);
			border-radius: 100%;
			text{
				display: flex;
				width: 20rpx;
				height: 20rpx;
				border-left: 2rpx solid #FFFFFF;
				border-bottom: 2rpx solid #FFFFFF;
				transform: rotate(45deg);
			}
		}
		.action{
			background-color: transparent;
			text{
				border-color: #555555;
			}
		}
	}
	//播放器弹出工具
	.player-tool {
		width: 100%;
		height: 60rpx;
		background-image: linear-gradient(0deg, rgba(0, 0, 0, .6), transparent);
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: absolute;
		left: 0;
		padding: 0 45rpx;
		transition: all 0.3s;
		.tools {
			height: 100%;
			width: auto;
			display: flex;
			align-items: center;
 
			.full-screen {
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
 
				.iconfont {
					color: #fff;
					font-weight: bold;
 
				}
			}
 
			.cruise {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 25rpx;
 
				.iconfont {
					color: #E45A3E;
					font-size: 45rpx;
				}
			}
		}
 
	}
	.hongbaoyu{
		top: 0;
		left: 0;
		position: fixed;
		width: 100vw;
		height: 100vh;
		overflow: hidden !important;
		background:rgba(0, 0, 0, .5);
		background-size: 100% 100%;
		background-repeat: no-repeat;
		z-index: 111;
		.top {
			width: 100%;
			height: 100rpx;
			line-height: 100rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		
			.left,
			.right {
				width: 50%;
				color: yellow;
				text-align: center;
			}
		}
		
		.start {
			width: 100%;
			height: 100vh;
			background-image: url(@/static/redBoxRain/bg.jpg);
			background-size: 100% 100%;
			background-repeat: no-repeat;
		
			.btn {
				position: absolute;
				bottom: 20%;
				left: 30%;
				width: 40%;
				height: 70rpx;
				color: yellow;
				text-align: center;
				line-height: 70rpx;
				border: 1rpx solid yellow;
				border-radius: 50rpx;
			}
		}
		
		.ready {
			position: fixed;
			top: 45%;
			color: yellow;
			font-size: 80rpx;
			font-weight: bold;
			width: 100%;
			text-align: center;
		}
		
		.redBox {
			position: relative;
			.red {
				position: absolute;
				animation: rain 20s linear 1 forwards;
			}
		
		}
		
		.endBox {
			position: absolute;
			top: 30%;
			left: 15%;
			width: 70%;
			height: 40vh;
			z-index: 99;
			background-color: #fff;
			text-align: center;
		
			.head {
				width: 100%;
				height: 10vh;
				line-height: 10vh;
				font-size: 35rpx;
				font-weight: bold;
				color: red;
			}
		
			.info {
				.star {
					.star-item {
						width: 10%;
						display: inline-block;
					}
				}
				
				.tips{
					margin: 5vh auto;
				}
				
				.btn{
					width: 80%;
					margin: 1vh auto;
					height: 6vh;
					line-height: 6vh;
					background-color: yellow;
					border-radius: 40rpx;
					font-weight: bold;
					color: #646464;
				}
			}
		}
		
		@keyframes rain {
			0% {
				transform: translateY(0);
			}
		
			100% {
				transform: translateY(120vh);
			}
		}
	}
</style>
